package com.lykj.llw.box.ui.activity.agent

import android.os.Bundle
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.ChooseGameAdapter
import com.lykj.llw.box.adapter.ChooseServerAdapter
import com.lykj.llw.box.adapter.agent.AgentDataQueryAdapter
import com.lykj.llw.box.data.bean.response.ChooseGameResponse
import com.lykj.llw.box.data.bean.response.agent.AgentLookEarningResponse
import com.lykj.llw.box.databinding.ActAgentDataQueryBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 代理数据查询
 * ================================================
 *
 * @author gosha
 * @date 2023/11/14-15:25
 */
class AgentDataQueryActivity : BaseActivity() {
    lateinit var binding: ActAgentDataQueryBinding

    private var mTextWatcher: TextWatcher? = null
    private val mAdapter = ChooseGameAdapter()
    private val mData = ArrayList<ChooseGameResponse.DataDTO>()
    private var mSelectPlayerId = -1

    private val mPlayerAdapter = AgentDataQueryAdapter()
    private val mPlayerData = ArrayList<AgentLookEarningResponse.DataDTO.RowsDTO>()

    private var currentPage = 1
    private val pageSize = 10
    private var totalPage = 1

    //    private var mIsShow = false
    private var mIsSet = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActAgentDataQueryBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "数据查询"
        binding.titleBar.tvRightOption.visibility = View.GONE
        binding.vEmpty.tvDesc.text = "暂无收益数据"

//        initRCV()
        initRCVPlayer()
    }

//    private fun initRCV() {
//        val linearLayoutManager = LinearLayoutManager(this)
//        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
//        binding.rcvChoose.layoutManager = linearLayoutManager
//        binding.rcvChoose.setHasFixedSize(true)
//
//        val dividerItemDecoration = LinearDividerItemDecoration(
//            this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
//        )
//        dividerItemDecoration.setDivider(
//            resources.getDrawable(
//                R.drawable.divider_5dp, resources.newTheme()
//            )
//        )
//        binding.rcvChoose.addItemDecoration(dividerItemDecoration, 0)
//        mAdapter.data = mData
//        mAdapter.setOnItemClickListener { adapter, view, position ->
//            mSelectPlayerId = mData[position].id
//
//            mIsSet = true
//            //隐藏列表
//            binding.etChoosePlayer.setText("${mData[position].name}")
//            binding.rcvChoose.visibility = View.GONE
//            binding.ivChoose.setImageResource(R.mipmap.ic_pull_down)
//
//
//            obtainPlayerData(mData[position].id)
//        }
//        binding.rcvChoose.adapter = mAdapter
//    }

    private fun initRCVPlayer() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvPlayerEarning.layoutManager = linearLayoutManager
        binding.rcvPlayerEarning.setHasFixedSize(true)
        mPlayerAdapter.data = mPlayerData
        binding.rcvPlayerEarning.adapter = mPlayerAdapter
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    //获取下拉玩家账号
    private fun obtainChoosePlayer(name: String) {
    }

    //获取玩家数据
    private fun obtainPlayerData(usename: String) {
        clearBodyParam()
        initBodyParam()
        bodyParams["pageNo"] = currentPage
        bodyParams["pageSize"] = pageSize
        bodyParams["username"] = usename
        RetrofitManager.instance.obtainEarningRecord(bodyParams,
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this@AgentDataQueryActivity, d)
                }

                override fun specificHandle(responseBody: String) {
                    val bean =
                        GsonUtils.fromJson(responseBody, AgentLookEarningResponse::class.java)
                    totalPage = bean.data.totalPage
                    if (!bean.data.rows.isNullOrEmpty()) {
                        mPlayerData.addAll(bean.data.rows)

                        if (currentPage == 1) {
                            binding.lltContainer.visibility = View.VISIBLE
                            binding.vEmpty.root.visibility = View.GONE
                        }
                    } else {
                        if (currentPage == 1) {
                            binding.lltContainer.visibility = View.GONE
                            binding.vEmpty.root.visibility = View.VISIBLE
                        }
                    }

                    mPlayerAdapter.notifyDataSetChanged()
                }

                override fun handleException(ret: String, msg: String?) {
                    msg?.let {
                        ToastUtils.showShort(this@AgentDataQueryActivity, it)
                    }
                }
            })
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.srfEarning.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                currentPage = 1
                mData.clear()
                mAdapter.notifyDataSetChanged()

                mPlayerData.clear()
                mPlayerAdapter.notifyDataSetChanged()

                obtainPlayerData(binding.etChoosePlayer.text.toString())

                refreshLayout.finishRefresh(500, true, false)
                refreshLayout.resetNoMoreData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (currentPage == totalPage) {
                    refreshLayout.finishLoadMoreWithNoMoreData()
                    ToastUtils.showShort(this@AgentDataQueryActivity, "没有更多数据了")
                    return
                }
                refreshLayout.finishLoadMore(500, true, false)
                currentPage++
                obtainPlayerData(binding.etChoosePlayer.text.toString())
            }
        })

//        mTextWatcher = object : TextWatcher {
//            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//            }
//
//            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//            }
//
//            override fun afterTextChanged(s: Editable?) {
////                if (!mIsSet) {
//                if (!binding.etChoosePlayer.text.toString().isNullOrBlank()) {
//                    obtainPlayerData(binding.etChoosePlayer.text.toString())
//                }
////                } else {
////                    mIsSet = false
////                }
//            }
//        }
        binding.etChoosePlayer.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (!binding.etChoosePlayer.text.toString().isNullOrBlank()) {
                    mPlayerData.clear()
                    mPlayerAdapter.notifyDataSetChanged()
                    obtainPlayerData(binding.etChoosePlayer.text.toString())
                } else {
                    ToastUtils.showShort(this@AgentDataQueryActivity, "请输入要搜索的玩家账号")
                }
            }
            true
        }
//        binding.etChoosePlayer.addTextChangedListener(mTextWatcher)

        binding.ivDelete.clickWithTrigger(250) {
            KeyboardUtils.hideSoftInput(this)
            binding.etChoosePlayer.setText("")
        }

        binding.root.clickWithTrigger(100) {
//            mIsSet = false
            //隐藏列表
            binding.rcvChoose.visibility = View.GONE
            binding.ivChoose.setImageResource(R.mipmap.ic_pull_down)
        }

        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (it == 0) {
                binding.etChoosePlayer.clearFocus()
            }
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}